package com.kurumi.autoprint.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kurumi.autoprint.enums.FeeRouteEnum;
import com.kurumi.autoprint.pojo.MrPrintDetail;
import com.kurumi.autoprint.enums.OrderStatusEnum;
import com.kurumi.autoprint.pojo.print.PrintMrOrder;
import com.kurumi.autoprint.service.ChinaUmsPayService;
import com.kurumi.autoprint.service.order.PrintMrOrderService;
import com.kurumi.autoprint.util.ExceptionUtil;
import com.kurumi.autoprint.util.IpUtil;
import com.kurumi.autoprint.util.JsonUtil;
import com.kurumi.autoprint.util.PayUtil;
import com.kurumi.autoprint.util.Result;

/**
 * 银联商务支付
 * 
 * @author 90669
 *
 */
@Controller
@RequestMapping("/pay")
public class ChinaUmsPayController {
	private Logger logger = LoggerFactory.getLogger(AutoPrintController.class);
	@Value("${PRINT_PIECE_FEE}")
	private String printPieceFee;

	@Value("${pay.ums.notify_url}")
	private String notifyUrl;
	
	@Value("${pay.ums.default.tid}")
	private String payUmsDefaultTid;
	
	@Value("${pay.um.tid.bind.ip}")
	private String payUmTidBindIp;

	@Autowired
	private ChinaUmsPayService chinaUmsPayService;

	@Autowired
	private PrintMrOrderService printMrOrderService;

	/**
	 * 获取银联商务二维码
	 * 
	 * @return
	 */
	@ResponseBody
	@PostMapping("/getUnionPayRrcode")
	public Result getUnionPayRrcode(HttpServletRequest request, PrintMrOrder printMrOrder, MrPrintDetail mrPrintDetail) {
		try {
			String ipAddress = null;
			
			try {
				 ipAddress = IpUtil.getIpAddr(request);
				 printMrOrder.setIp(ipAddress);
				 String tid = PayUtil.getTidByClientIp(ipAddress, payUmsDefaultTid, payUmTidBindIp);
				 
				 
				 printMrOrder.setSendAccount(tid);
				 
			} catch (Exception e) {
				logger.error("--调用银联生成二维码支付获取客户端ip地址异常,ipAddress={}, exceptionMsg={}", 
						ipAddress, ExceptionUtil.getStackTrace(e));
			}
			
			Result verifyResult = printMrOrder.fieldVerify(printMrOrder);

			if (!verifyResult.isSuccess()) {
				return verifyResult;
			}

			Result result = chinaUmsPayService.getPayQsCode(printMrOrder, ipAddress,payUmTidBindIp);

			if (!result.isSuccess()) {
				return result;
			}

			// 添加订单
			printMrOrder.setPrintUnitPrice(new BigDecimal(printPieceFee));
			printMrOrder.setFeeRouteCode(FeeRouteEnum.YING_LIAN_PAY.getValue());
			printMrOrder.setFeeRouteName(FeeRouteEnum.YING_LIAN_PAY.getName());
			
			
			try {
				  Result r1 = printMrOrderService.insertPrintMrOrder(printMrOrder, mrPrintDetail);
				  
				  if (!r1.isSuccess()) {
					  return r1;
				  }
			} catch (Exception e) {
				logger.error("添加订单信息数据库异常:exceptionMsg=" + ExceptionUtil.getStackTrace(e));
				return new Result(false, "添加订单信息数据库异常:" + ExceptionUtil.getStackTrace(e), null, 500);
			}

			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取银联商务二维码异常, ordreParam={}, exceptionMsg={}", printMrOrder.toString(),
					ExceptionUtil.getStackTrace(e));

			return new Result(false, "系统异常:" + ExceptionUtil.getStackTrace(e));
		}

	}

	/**
	 * 获取银联商务二维码
	 * 
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/notify")
	public void notify(HttpServletRequest request, HttpServletResponse response) throws IOException {

		logger.info("进入支付回调---------------------------");

		Map<String, String[]> properties = request.getParameterMap();
		System.out.println("回调返回参数----start");
		// 返回值Map
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {

			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();

			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString();
			}

			returnMap.put(name, value);

		}

		if(MapUtils.isEmpty(returnMap)) {
			logger.info("银联商务通过notify url 返回参数为空!");
			response.getWriter().println("FAILED");
			return;
		}
		String status = MapUtils.getString(returnMap, "billStatus");
		String billNo = MapUtils.getString(returnMap, "billNo");

		logger.info("银联商务返回状态和订单号分别为:billStatus={},billNo={}",status,billNo);
		//PAID  UNPAID  REFUND  CLOSED  UNKNOWN
		if ("PAID".equals(status)) {
			
			logger.info("订单号为{}的银联商务订单支付成功!",billNo);
			
			//支付成功根据订单号查询订单更改订单状态为已支付
			printMrOrderService.updatePrintMrOrderStatusByBillNo(billNo,OrderStatusEnum.TRADE_SUCCESS.getValue());
			response.getWriter().println("SUCCESS");
		} else if ("UNPAID".equals(status)) {
			//未支付不用修改状态
			logger.info("订单号为{}的银联商务订单未支付!",billNo);
			response.getWriter().println("FAILED");
		} else {
			logger.info("订单号为{}的银联商务订单失败!",billNo);
			printMrOrderService.updatePrintMrOrderStatusByBillNo(billNo,OrderStatusEnum.TRADE_FAIL.getValue());
			response.getWriter().println("FAILED");
		}

		System.out.println("回调返回参数----end");

		logger.info("支付回调响应参数:" + JsonUtil.objectToJson(returnMap));
	}
	
	
	
//	/**
//	 *根据订单号查询订单信息
//	 * 
//	 * @return
//	 */
//	@ResponseBody
//	@RequestMapping("/getprintMrOrderByOrderNum")
//	public Result getprintMrOrderByOrderNum(String orderNum) {
//		Result result = null;
//		try {
//			if(StringUtils.isEmpty(orderNum)) {
//				return new Result(false,"订单号不可为空!");
//			}
//		
//			PrintMrOrder printMrOrder = printMrOrderService.getprintMrOrderByOrderNum(orderNum);
//			if(printMrOrder!=null) {
//			 	Integer status = printMrOrder.getStatus();
//			 	if(status==null) {
//			 		result = new Result(false,"支付 不存在!");
//			 		return result;
//			 	}
//			 	if(status==OrderStatusEnum.TRADE_SUCCESS.getValue()) {
//			 		result = new Result(true,"支付成功!");
//			 		return result;
//			 	}
//			}else {
//				
//				result = new Result(false,"订单不存在!");
//		 		return result;
//			}
//			
//			Integer status = printMrOrder.getStatus();
//			
//			if(status.intValue() == OrderStatusEnum.TRADE_SUCCESS.getValue().intValue()) {
//			 		return new Result(true,"支付成功!");
//			} else {
//				 return new Result(false,"未支付!");
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			logger.error("查询订单号失败,异常信息, orderNum={}, exceptionMsg={}", orderNum,
//					ExceptionUtil.getStackTrace(e));
//
//			return new Result(false, "系统异常:" + ExceptionUtil.getStackTrace(e));
//		}
//
//	}
//	
	
	/**
	 *根据订单号查询订单信息
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getprintMrOrderByOrderNum1")
	public Result getprintMrOrderByOrderNum(String orderNum) {
		Result result = null;
		try {
			if(StringUtils.isEmpty(orderNum)) {
				return new Result(false,"订单号不可为空!");
			}
		
			PrintMrOrder printMrOrder = printMrOrderService.getprintMrOrderByOrderNum(orderNum);
			if(printMrOrder!=null) {
			 	Integer status = printMrOrder.getStatus();
			 	if(status==null) {
			 		result = new Result(false,"支付 不存在!");
			 		return result;
			 	}
			 	if(status==OrderStatusEnum.TRADE_SUCCESS.getValue()) {
			 		result = new Result(true,"支付成功!");
			 		return result;
			 	}
			}else {
				
				result = new Result(false,"订单不存在!");
		 		return result;
			}
			
			Integer status = printMrOrder.getStatus();
			
			if(status.intValue() == OrderStatusEnum.TRADE_SUCCESS.getValue().intValue()) {
			 		return new Result(true,"支付成功!");
			} else {
				 return new Result(false,"未支付!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询订单号失败,异常信息, orderNum={}, exceptionMsg={}", orderNum,
					ExceptionUtil.getStackTrace(e));

			return new Result(false, "系统异常:" + ExceptionUtil.getStackTrace(e));
		}

	}
	
	
	/**
	 *根据订单号查询订单信息
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getprintMrOrderByOrderNum")
	public Result queryNetpayByOrderNo(String orderNum) {
		try {
			if(StringUtils.isEmpty(orderNum)) {
				return new Result(false,"订单号不可为空!");
			}
			
			
			Result result = chinaUmsPayService.queryNetpayByOrderNo(orderNum);

			if (!result.isSuccess()) {
				return result;
			}
			
			String billStatus = (String) result.getData();
			if(StringUtils.isEmpty(billStatus)) {
				return new Result(false,"订单状态不存在!");
			}
			
			if(billStatus.equals("PAID")) {
				//支付成功根据订单号查询订单更改订单状态为已支付
				printMrOrderService.updatePrintMrOrderStatusByBillNo(orderNum,OrderStatusEnum.TRADE_SUCCESS.getValue());
				return new Result(true,"订单支付成功!");
			}else if(billStatus.equals("UNPAID")) {
				return new Result(false,"订单未支付!");
			}else {
				return new Result(false,"订单支付失败!");
			}
		}catch(Exception e) {
			e.printStackTrace();
			return new Result(false,"订单支付失败!失败原因:"+e.getMessage(),500) ;   
		}
			
			
	

	}
	
	
	

}
